package com.lej.location

import android.content.Context

import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption

/**
 * 高德定位
 */
open class AmapLocation : LocationInterface {

    //定位功能
    private var locationClient: AMapLocationClient? = null

    /**
     * 默认定位参数
     *
     * @return
     */
    private val defaultOption: AMapLocationClientOption
        get() {
            val mOption = AMapLocationClientOption()
            mOption.locationMode =
                AMapLocationClientOption.AMapLocationMode.Hight_Accuracy//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
            mOption.isGpsFirst = false//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
            mOption.httpTimeOut = 30000 //可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
            mOption.interval = 2000//可选，设置定位间隔。默认为2秒
            mOption.isNeedAddress = true//可选，设置是否返回逆地理地址信息。默认是true
            mOption.isOnceLocation = true//可选，设置是否单次定位。默认是false
            //可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
            mOption.isOnceLocationLatest = false
            mOption.isLocationCacheEnable = false// 设置是否开启缓存
            AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTPS)//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
            return mOption
        }

    override fun init(context: Context, listener: LocationListener) {
        //初始化client
        locationClient = AMapLocationClient(context.applicationContext).apply {
            //设置定位参数
            setLocationOption(defaultOption)
            // 设置定位监听
            setLocationListener { aMapLocation ->
                if (null != aMapLocation && aMapLocation.errorCode == 0) {  //定位成功
                    listener.success(transitionModel(aMapLocation))
                } else {
                    listener.error(
                        if (aMapLocation == null) "定位失败" else "${aMapLocation.errorCode}:${aMapLocation.errorInfo}"
                    )
                }
                stopLocation() //停止定位
            }
        }
    }

    /**
     * 开始定位
     */
    override fun startLocation() {
        locationClient?.startLocation()
    }

    override fun stopLocation() {
        locationClient?.stopLocation()
    }

    override fun destroyLocation() {
        locationClient?.onDestroy()
        locationClient = null
    }

    /**
     * 把高德定位model转换为 自用model
     */
    private fun transitionModel(aMapLocation: AMapLocation): LocationModel {
        return LocationModel().apply {
            city = aMapLocation.city
            province = aMapLocation.province
            district = aMapLocation.district
            lat = aMapLocation.latitude
            lon = aMapLocation.longitude
        }
    }
}